package com.sap.health.tracker.threads;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.sap.health.tracker.R;
import com.sap.health.tracker.json.JSONFunctions;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class ProfileThread extends Activity implements
AdapterView.OnItemSelectedListener{

	// JSON Response node names
    private static String KEY_SUCCESS = "success";
    private TextView mGetPatientsErrorMsg;
	private TableLayout mTable;
	
	private Context mCtx;
	private String mUserID;
	private String mSessionToken;
	
	private String mInputGender;
	private Spinner mGenderSpinner;
	private int mRulerColour = 0xFFDEDEDE;
	
	private int mItemsPopup = R.layout.popup;

	private ProgressDialog mLoadingDialog;
	
	/**
	 * Runs when Class is first created.
	 * @param ctx
	 */
    public ProfileThread(Context ctx, String userId, String sessionToken,
    		final TextView getPatientsErrorMsg,
    		final ImageView refresh,
    		final TableLayout table){
    	
    	this.mGetPatientsErrorMsg = getPatientsErrorMsg;
    	this.mTable = table;
    	this.mCtx = ctx;
    	this.mUserID = userId;
    	this.mSessionToken = sessionToken;
    	
    	refresh.setOnClickListener(new OnClickListener() {
         	public void onClick(View v) {
         		refresh();
         	}
         });  	
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // needed but not used.
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.profile_thread, menu);
        return true;
    }
    /**
     * Get user profile.
     */
    public void getProfile(){ 	
    	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			// let the user know it's busy.
            	createProgressDialog();
            	// connect to server and get profile info.
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.getDoctorProfile(mUserID, mSessionToken);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();               		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			JSONObject jsonProfile = json.getJSONObject("user");               		                			
                			             			
                			final String firstname = jsonProfile.getString("firstname");
                			final String lastname = jsonProfile.getString("lastname");
                			//add both the first and last name to get the full name.
                			final String fullname = firstname + " " + lastname;               			
                			final String username = jsonProfile.getString("username");
                			final String email = jsonProfile.getString("email");
                			final String address1 = jsonProfile.getString("address1");
                			final String address2 = jsonProfile.getString("address2");
                			final String city = jsonProfile.getString("city");
                			final String state = jsonProfile.getString("state");
                			final String country = jsonProfile.getString("country");
                			final String postal = jsonProfile.getString("postal");
                			final String contact = jsonProfile.getString("contact");
                			final String gender = jsonProfile.getString("gender");
                			final String dob = jsonProfile.getString("dob");
                			final int year = jsonProfile.getInt("year");
                			final int month = jsonProfile.getInt("month");
                			final int day = jsonProfile.getInt("day");               			
                			profileUiHandler(username, email, fullname, gender, address1, address2, city, state, country, postal, contact, dob, year, month, day, firstname, lastname);             			                                                        
                		}else{
                			//let the user know there was an error.
       		        	 	errorMessage("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 errorMessage("Network Connection Error");		        	 
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    /**
     * UI handler for profile info.
     * @param username
     * @param email
     * @param fullname
     * @param gender
     * @param address1
     * @param address2
     * @param city
     * @param state
     * @param country
     * @param postal
     * @param contact
     * @param dob
     * @param year
     * @param month
     * @param day
     * @param firstname
     * @param lastname
     */
    private void profileUiHandler(
    		final String username,
    		final String email,
    		final String fullname, 
    		final String gender,
    		final String address1,
    		final String address2,
    		final String city,
    		final String state,
    		final String country,
    		final String postal,
    		final String contact,
    		final String dob, 
    		final int year, 
    		final int month, 
    		final int day,
    		final String firstname, 
    		final String lastname){
    	
    	runOnUiThread(new Runnable() {
			public void run() {			
				//clear table contents
				mTable.removeAllViews();							
				/**************
				 * username
				 ***************/
				TableRow usernameRow = new TableRow(mCtx);				
				usernameRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your username and is needed to login in.");               	                	
	                    return true;
	                }
	            });				
	           	TextView usernameTx = new TextView(mCtx);
	           	usernameTx.setText("Username: " + username);
	           	usernameTx.setTextSize(18f);
	           	 // add views to the row
	           	usernameRow.addView(usernameTx); // you would actually want to set properties on this before adding it
	           	usernameRow.setPadding(10, 10, 0, 10);
	           	 // add the row to the table layout
	           	 mTable.addView(usernameRow);	           	 	           	
	           	//  Used for creating a horizontal line to separate .                     	           	 
	           	View ruler1 = new View(mCtx); ruler1.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler1, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));				
	           	/*******************
				 * email
				 *******************/
				TableRow emailRow = new TableRow(mCtx);				
				emailRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your email address and will allow " +
	                    		"your connections to contact you.");               	                	
	                    return true;
	                }
	            });				
	           	TextView emailTx = new TextView(mCtx);
	           	emailTx.setText("Email: " + email);
	           	emailTx.setTextSize(18f);
	           	 // add views to the row
	           	emailRow.addView(emailTx); // you would actually want to set properties on this before adding it
	           	emailRow.setPadding(10, 10, 0, 10);
	           	// add the row to the table layout
	           	mTable.addView(emailRow);	           	 	           	
	           	//  Used for creating a horizontal line to separate .                     	           	 
	           	View ruler2 = new View(mCtx); ruler2.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler2, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));	           	
	           	/****************
	           	 * fullname
	           	 **************/	           	
	           	TableRow fullnameRow = new TableRow(mCtx);	           	 
	           	fullnameRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your full name. Click it to edit.");               	                	
	                    return true;
	                }
	            });	           	 
	           	TextView fullnameTx = new TextView(mCtx);
	           	fullnameTx.setText("Fullname: " + fullname);
	           	fullnameTx.setTextSize(18f);
	           	fullnameRow.setOnClickListener(new View.OnClickListener() {
	           		 public void onClick(View view) {                	                	                 	      				
	    				profileNameDialog("Edit Fullname",
	    						firstname, lastname); 		
	    			}
	           	 });	           	 
	           	 // add views to the row
	           	 fullnameRow.addView(fullnameTx); // you would actually want to set properties on this before adding it
	           	 fullnameRow.setPadding(10, 10, 0, 10);
	           	 // add the row to the table layout
	           	 mTable.addView(fullnameRow);	           	 
	           	//Used for creating a horizontal line to separate .	                   	           	 
	           	View ruler = new View(mCtx); ruler.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));	           		           	
	           	/****************
	           	 * gender
	           	 **************/           	
	           	TableRow genderRow = new TableRow(mCtx);	           	 
	           	genderRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your gender. Click it to edit.");               	                	
	                    return true;
	                }
	            });	           	
	           	TextView genderTx = new TextView(mCtx);
	           	genderTx.setText("Gender: " + gender);
	           	genderTx.setTextSize(18f);           	 
	           	genderRow.setOnClickListener(new View.OnClickListener() {
	    			public void onClick(View view) {                	                	                 	      				
	    				profileGenderDialog("Edit Gender", gender);	    		
	    			}
	    		});	           	 
	           	// add views to the row
	           	genderRow.addView(genderTx); // you would actually want to set properties on this before adding it
	           	genderRow.setPadding(10, 10, 0, 10);
	           	// add the row to the table layout
	           	mTable.addView(genderRow);        	            	
	           	// Used for creating a horizontal line to separate .	           	          	           	 
	           	View ruler3 = new View(mCtx); ruler3.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler3, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));
	           	/****************
	           	 * address
	           	 **************/           	
	           	TableRow addressRow = new TableRow(mCtx);	           	 
	           	addressRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your address. Click it to edit.");               	                	
	                    return true;
	                }
	            });	           	 
	           	TextView addressTx = new TextView(mCtx);
	           	addressTx.setText("Address: " + address1);
	           	addressTx.setTextSize(18f);	           	 
	           	addressRow.setOnClickListener(new View.OnClickListener() {
	    			public void onClick(View view) {                	                	                 	      				
	    				addressDialog("Edit Address", address1, address2, city, state, country, postal);	    		
	    			}
	    		});	           	 
	           	// add views to the row
	           	addressRow.addView(addressTx); // you would actually want to set properties on this before adding it
	           	addressRow.setPadding(10, 10, 0, 10);
	           	 // add the row to the table layout
	           	 mTable.addView(addressRow);        	 	           	
	           	// Used for creating a horizontal line to separate .	           	          	           	 
	           	View ruler4 = new View(mCtx); ruler4.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler4, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));	           	
	           	/****************
	           	 * contact
	           	 **************/           	
	           	TableRow contactRow = new TableRow(mCtx);           	 
	           	contactRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your contact number. Click it to edit.");               	                	
	                    return true;
	                }
	            });	           	 
	           	TextView contactTx = new TextView(mCtx);
	           	contactTx.setText("Contact: " + contact);
	           	contactTx.setTextSize(18f);	           	 
	           	contactRow.setOnClickListener(new View.OnClickListener() {
	    			public void onClick(View view) {                	                	                 	      				
	    				contactDialog("Edit Contact", contact);	    		
	    			}
	    		});	           	 
	           	// add views to the row
	           	contactRow.addView(contactTx); // you would actually want to set properties on this before adding it
	           	contactRow.setPadding(10, 10, 0, 10);
	           	 // add the row to the table layout
	            mTable.addView(contactRow);        	 	           	
	           	// Used for creating a horizontal line to separate .	           	          	           	 
	           	View ruler5 = new View(mCtx); ruler5.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler5, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));	           	
	           	/****************
	           	 * date of birth
	           	 **************/           	
	           	TableRow dobRow = new TableRow(mCtx);	           	 
	           	dobRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("This is your date of birth. Click it to edit.");               	                	
	                    return true;
	                }
	            });	           	 
	           	TextView dobTx = new TextView(mCtx);
	           	dobTx.setText("Date of Birth: " + dob);
	           	dobTx.setTextSize(18f);	           	 
	           	dobRow.setOnClickListener(new View.OnClickListener() {
	    			public void onClick(View view) {                	                	                 	    				
	    				datePicker("Edit Date of Birth", year, month, day);
	    			}
	    		});	           	 
	           	// add views to the row
	           	dobRow.addView(dobTx); // you would actually want to set properties on this before adding it
	           	dobRow.setPadding(10, 10, 0, 10);
	           	 // add the row to the table layout
	           	mTable.addView(dobRow);        	 	           	
	           	// Used for creating a horizontal line to separate .	           	          	           	 
	           	View ruler6 = new View(mCtx); ruler.setBackgroundColor(mRulerColour);
	           	mTable.addView(ruler6, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));	           		           		           	
            }
		});
    }
    /**
     * Handles the data picker.
     * @param title
     * @param year
     * @param month
     * @param day
     */
    private void datePicker(String title, int year, int month, int day){
		  // month is 0 based, so minus one.
    	final DatePickerDialog picker = new DatePickerDialog(mCtx, null, // instead of a listener 
			year, month-1, day);  	
    	// resets back to date format when picker is selected
    	picker.setTitle(title);
	    picker.setCancelable(true);
	    picker.setCanceledOnTouchOutside(true);
	    picker.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
	        new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                System.out.println("Picker " + "Correct behavior!");
	                String year = String.valueOf(picker.getDatePicker().getYear());
	                // month is 0 based, so add one.
	                String month = String.valueOf(picker.getDatePicker().getMonth()+1);
	                String day = String.valueOf(picker.getDatePicker().getDayOfMonth());
	                saveDOBThread(year, month, day);
	            }
	        });
	    picker.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", 
	        new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	// Don't need to do anything. Just a place holder.
	            	System.out.println("Picker " + "Cancel!");
	            }
	        });
	    picker.show();    
    }
    /**
     * Save user date of birth.
     * @param year
     * @param month
     * @param day
     */
    public void saveDOBThread(final String year, final String month, final String day){  	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			createProgressDialog();
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.saveDOB(mUserID, mSessionToken,
                		year, month, day);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {              		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){        	
            				runOnUiThread(new Runnable() {
                				public void run() {
                					// reload the profile layout.
                					refresh();
                				}
                			});             		                			                                                      
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 simpleDialog("Network Connection Error");
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }  
    /**
     * Gender Dialog.
     * @param title
     * @param genderStr
     */
    private void profileGenderDialog(String title, String genderStr){
		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(mItemsPopup);
		dialog.setTitle(title);  
		// Create row
		TableLayout genderRow = new TableLayout(mCtx);
		// Create Spinner
		mGenderSpinner = new Spinner(mCtx);
        mGenderSpinner.setOnItemSelectedListener(this);
		// Add values to spinner. 
      	List<String> list = new ArrayList<String>();
		list.add("Male");
		list.add("Female");
		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter <String>(mCtx,
		        android.R.layout.simple_spinner_dropdown_item, list);
		mGenderSpinner.setAdapter(spinnerArrayAdapter);
		// grab the current gender value and set the spinner to it.
		if(genderStr.equalsIgnoreCase("male")){
			mGenderSpinner.setSelection(0);
		} else {
			mGenderSpinner.setSelection(1);
		}		
		// Create Button
      	Button saveBtn = new Button(mCtx);
      	// Set text to button 
      	saveBtn.setText("Save");    	 
      	// add spinner to the row
      	genderRow.addView(mGenderSpinner);
      	// Add padding.
      	genderRow.setPadding(10, 20, 0, 0);       
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	TableLayout btnTable = (TableLayout) dialog.findViewById(R.id.btnTable);    
      	// add the row to the table layout
      	dialogTable.addView(genderRow);     	
      	btnTable.addView(saveBtn);	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});		
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Gender: " + mInputGender);
				saveGenderThread(dialog, mInputGender);
			}
		});
	
   
		dialog.show();
	}
    /**
     * Save user gender.
     * @param dialog
     * @param inputGender
     */
    public void saveGenderThread(final Dialog dialog, final String inputGender){  	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			createProgressDialog();
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.saveGender(mUserID, mSessionToken,
                		inputGender);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {             		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){        	
            				runOnUiThread(new Runnable() {
                				public void run() {
                					// close save dialog 
                					dialog.dismiss(); 
                					// reload the profile layout.
                					refresh();
                				}
                			});             		                			                                                      
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 simpleDialog("Network Connection Error");
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    
    // Runs when item in Spinner is selected
    public void onItemSelected(AdapterView<?> parent, View view, 
            int pos, long id) {
        // An item was selected. You can retrieve the selected item using
    	if (parent == mGenderSpinner){
			switch (pos){
		    	case 0:
		    		mInputGender = "Male";
		    		break;
		    	case 1:
		    		mInputGender = "Female";
		    		break;
		    	default:
		    		mInputGender = "Male";
		    		break;
	    	}
    	}    	
    }
    /**
     * User contact number dialog.
     * @param title
     * @param contact
     */
    private void contactDialog(String title, 
    		String contact){
		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(mItemsPopup);
		dialog.setTitle(title); 
		TableRow row = new TableRow(mCtx);
      	// create text view.
      	final EditText text = new EditText(mCtx);
      	text.setInputType(InputType.TYPE_CLASS_PHONE);
      	text.setText(contact);
      	text.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));      	 
      	Button saveBtn = new Button(mCtx);
      	saveBtn.setText("Save");   	 
      	// add views to the row
      	row.addView(text);
      	row.setPadding(10, 20, 0, 0);
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	TableLayout btnTable = (TableLayout) dialog.findViewById(R.id.btnTable);    
      	// add the row to the table layout
      	dialogTable.addView(row);
      	btnTable.addView(saveBtn);  	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});		
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Retrieve text input from user
				String input = text.getText().toString();
				saveContactThread(dialog, input);
				
			}
		});	  
		dialog.show();
	}
    /**
     * Save User Contact number
     * @param dialog
     * @param contact
     */
    public void saveContactThread(final Dialog dialog, final String contact){  	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			createProgressDialog();
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.saveContact(mUserID, mSessionToken,
                		contact);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {               		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){        	
            				runOnUiThread(new Runnable() {
                				public void run() {
                					// close save dialog 
                					dialog.dismiss(); 
                					// reload the profile layout.
                					refresh();
                				}
                			});             		                			                                                      
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 simpleDialog("Network Connection Error");
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    /**
     * User address dialog.
     * @param title
     * @param address1
     * @param address2
     * @param city
     * @param state
     * @param country
     * @param postal
     */
    private void addressDialog(
    		String title, 
    		String address1, 
    		String address2, 
    		String city, 
    		String state,
    		String country,
    		String postal){

		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(mItemsPopup);
		dialog.setTitle(title);   
		TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
     	TableLayout btnTable = (TableLayout) dialog.findViewById(R.id.btnTable); 		
     	TableRow address1Row = new TableRow(mCtx);
      	// create text view.
      	final EditText address1Text = new EditText(mCtx);
      	address1Text.setText(address1);
      	address1Text.setHint("Address 1");
      	address1Text.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
      	// add views to the row
      	address1Row.addView(address1Text);
      	address1Row.setPadding(10, 20, 0, 0); 
      	// add the row to the table layout
       	dialogTable.addView(address1Row);     	 
       	TableRow address2Row = new TableRow(mCtx);
     	 // create text view.
     	 final EditText address2Text = new EditText(mCtx);
     	address2Text.setText(address2);
     	address2Text.setHint("Address 2");
     	address2Text.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
     // add views to the row
     	address2Row.addView(address2Text);
     	address2Row.setPadding(10, 20, 0, 0); 
     // add the row to the table layout
      	dialogTable.addView(address2Row);     	
      	TableRow cityRow = new TableRow(mCtx);
    	// create text view.
    	final EditText cityText = new EditText(mCtx);
    	cityText.setText(city);
    	cityText.setHint("City");
    	cityText.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
    	// add views to the row
    	cityRow.addView(cityText);
    	cityRow.setPadding(10, 20, 0, 0); 
    	// add the row to the table layout
     	dialogTable.addView(cityRow);
     	TableRow stateRow = new TableRow(mCtx);
	   	// create text view.
	   	final EditText stateText = new EditText(mCtx);
	   	stateText.setText(state);
	   	stateText.setHint("State");
	    stateText.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
	    // add views to the row
	    stateRow.addView(stateText);
	    stateRow.setPadding(10, 20, 0, 0); 
	    // add the row to the table layout
    	dialogTable.addView(stateRow);   	
    	TableRow countryRow = new TableRow(mCtx);
	   	// create text view.
	   	final EditText countryText = new EditText(mCtx);
	   	countryText.setText(country);
	   	countryText.setHint("Country");
	   	countryText.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
	    // add views to the row
	    countryRow.addView(countryText);
	    countryRow.setPadding(10, 20, 0, 0); 
	    // add the row to the table layout
    	dialogTable.addView(countryRow);   	
    	TableRow postalRow = new TableRow(mCtx);
	   	// create text view.
	   	final EditText postalText = new EditText(mCtx);
	   	postalText.setText(postal);
	   	postalText.setHint("Postal");
	   	postalText.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
	    // add views to the row
	   	postalRow.addView(postalText);
	   	postalRow.setPadding(10, 20, 0, 0); 
	    // add the row to the table layout
    	dialogTable.addView(postalRow);     	      	
      	Button saveBtn = new Button(mCtx);
      	saveBtn.setText("Save");   	   	  	    	 
      	btnTable.addView(saveBtn);  	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});		
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Retrieve text input from user				
				String address1 = address1Text.getText().toString();
				String address2 = address2Text.getText().toString();
				String city = cityText.getText().toString();
				String state = stateText.getText().toString();
				String country = countryText.getText().toString();
				String postal = postalText.getText().toString();				
				String address = 
					address1 +"|" + 
					address2 +"|" + 
					city +"|" + 
					state +"|" + 
					country +"|" + 
					postal;
				saveAddressThread(dialog, address);				
			}
		});	   
		dialog.show();
	}
    /**
     * Save user address.
     * @param dialog
     * @param address
     */
    public void saveAddressThread(final Dialog dialog, final String address){  	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			createProgressDialog();
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.saveAddress(mUserID, mSessionToken,
                		address);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {              		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){        	
            				runOnUiThread(new Runnable() {
                				public void run() {
                					// close save dialog 
                					dialog.dismiss(); 
                					// reload the profile layout.
                					refresh();
                				}
                			});             		                			                                                      
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 simpleDialog("Network Connection Error");
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    /**
     * Users full name dialog
     * @param title
     * @param firstname
     * @param lastname
     */
    private void profileNameDialog(String title, 
    		String firstname, String lastname){

		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(mItemsPopup);
		dialog.setTitle(title);  
		TableRow firstnameRow = new TableRow(mCtx);
		TableRow lastnameRow = new TableRow(mCtx);
      	// create text view.
      	final EditText firstnameTx = new EditText(mCtx);
      	final EditText lastnameTx = new EditText(mCtx);
      	//fill the width of the dialog.
      	firstnameTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
      	lastnameTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
      	Button saveBtn = new Button(mCtx);
      	firstnameTx.setText(firstname);
      	lastnameTx.setText(lastname);
      	saveBtn.setText("Save");  
      	// add views to the row
      	firstnameRow.addView(firstnameTx);
      	lastnameRow.addView(lastnameTx);
      	//btnRow.addView(saveBtn);       
      	firstnameRow.setPadding(10, 20, 0, 0);
      	lastnameRow.setPadding(10, 20, 0, 0);    
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	TableLayout btnTable = (TableLayout) dialog.findViewById(R.id.btnTable);    
      	 // add the row to the table layout
      	dialogTable.addView(firstnameRow);
      	dialogTable.addView(lastnameRow);
      	btnTable.addView(saveBtn);	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});	
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Retrieve text input from user
				String firstnameInput = firstnameTx.getText().toString();
				String lastnameInput = lastnameTx.getText().toString();
				saveNameThread(dialog, firstnameInput, lastnameInput);
				
			}
		}); 
		dialog.show();
	}   
    /**
     * Save users name.
     * @param dialog
     * @param firstname
     * @param lastname
     */
    public void saveNameThread(final Dialog dialog, final String firstname, final String lastname){  	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
    			createProgressDialog();
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.saveName(mUserID, mSessionToken,
                		firstname, lastname);
                 // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {               		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){        	
            				runOnUiThread(new Runnable() {
                				public void run() {
                					// close save dialog 
                					dialog.dismiss(); 
                					// reload the profile layout.
                					refresh();
                				}
                			});             		                			                                                      
                		}else{
                			//let the user know there was an error.
       		        	 	simpleDialog("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 simpleDialog("Network Connection Error");
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    /**
     * Simple dialog.
     * @param title
     */
    private void simpleDialog(final String title){
    	runOnUiThread(new Runnable() {
			public void run() {
				// custom dialog
				final Dialog dialog = new Dialog(mCtx);
				dialog.setContentView(mItemsPopup);
				dialog.setTitle(title);		 	
				Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
				// if button is clicked, close the custom dialog
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});		 
				dialog.show();
			}
		}); 		
	}
    /**
     * Reloads current layout.
     */
    private void refresh(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	getProfile();
            }
    	});
    }
    /**
     * Empty error message.
     */
    private void emptyErrorMessage(){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetPatientsErrorMsg.setText("");
             	mGetPatientsErrorMsg.setVisibility(View.INVISIBLE);
            }
		});
    }
    /**
     * Show error message.
     * @param error
     */
    private void errorMessage(final String error){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetPatientsErrorMsg.setText(error);
             	mGetPatientsErrorMsg.setVisibility(View.VISIBLE);
            }
		});
    }
    /**
     * Dismiss progress dialog.
     */
    private void dismissProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// hide progress spinner now that thread is finished.
            	//progressSpinner.setVisibility(View.INVISIBLE);
            	mLoadingDialog.dismiss();
            }
        });
    }
    /**
     * Create progress dialog.
     */
    private void createProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// show progress spinner to let the user know it's working.
            	//progressSpinner.setVisibility(View.VISIBLE);
            	mLoadingDialog = new ProgressDialog(mCtx);
                mLoadingDialog.setTitle("");
                mLoadingDialog.setMessage("Loading. Please wait...");
            	mLoadingDialog.show();
            }
        });
    }
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// do nothing.		
	}
	/**
	 * Help dialog.
	 * @param message
	 */
	private void helpDialog(final String message){
		
		// custom dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(R.layout.popup);
		dialog.setTitle("Help options");		
		TableRow noteRow = new TableRow(mCtx);
      	// create text view.
      	TextView noteTx = new TextView(mCtx);
      	noteTx.setText(message);
      	noteTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
      	// add views to the row
      	noteRow.addView(noteTx);   	 
      	noteRow.setPadding(10, 10, 0, 10);      
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	// add the row to the table layout
      	dialogTable.addView(noteRow);			
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		}); 
		dialog.show();	
	}
}
